//
//  BIDAddressBookViewController.m
//  cxgov
//
//  Created by mal on 16/3/5.
//  Copyright © 2016年 mal. All rights reserved.
//

#import "BIDAddressBookViewController.h"
#import "BIDMemberDetailViewController.h"
#import "BIDNode.h"

#import "BIDAddressBookCell.h"

static NSString *addressBookURL = @"userAndroid!gainDepUsers.action";

@interface BIDAddressBookViewController ()<BIDBaseListViewDelegate>
    {
        NSMutableArray *_originArr;
        NSArray *_srcArr;
        BOOL _bRegister;
        NSMutableArray *_relatedNodeArr;
    }
@end

@implementation BIDAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"部门通讯录";
    _relatedNodeArr = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], addressBookURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"userId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id responseObj, NSString *errMsg){
        if([responseObj isKindOfClass:[NSArray class]])
        {
            NSArray *arr = (NSArray*)responseObj;
            _srcArr = [[NSArray alloc] initWithArray:arr];
            [self transformDataFrom:arr];
        }
    }];
}
    
    - (NSArray *)transformDataFrom:(NSArray *)srcArr
    {
        if(srcArr && srcArr.count>0)
        {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentId=%@", @""];
            NSArray *filteredArr = [srcArr filteredArrayUsingPredicate:predicate];
            if(filteredArr.count > 0)
            {
                NSDictionary *tempDic = filteredArr[0];
                BIDNode *node = [[BIDNode alloc] init];
                node.nodeID = ANY2NSSTRING(tempDic[@"id"]);
                node.level = 0;
                node.isExpand = YES;
                node.parentID = @"";
                NSNumber *value = tempDic[@"isPerson"];
                node.isPerson = [value intValue]==1 ? YES : NO;
                node.data = [[NSDictionary alloc] initWithDictionary:tempDic];
                [self getChildrenByNode:node];
                //
                [self.dataSourceArr addObject:node];
                for(BIDNode *tempNode in node.childArr)
                {
                    [self.dataSourceArr addObject:tempNode];
                }
                [self.myTableView reloadData];
            }
        }
        return nil;
    }
    - (NSArray *)getChildrenByNode:(BIDNode *)parentNode
    {
        NSString *parentID = parentNode.nodeID;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentId=%@ OR self.parentId=%d", parentID, [parentID intValue]];
        NSArray *filteredArr = [_srcArr filteredArrayUsingPredicate:predicate];
        if(filteredArr && filteredArr.count>0)
        {
            for(NSDictionary *tempDic in filteredArr)
            {
                BIDNode *node = [[BIDNode alloc] init];
                node.level = parentNode.level + 1;
                node.data = [[NSDictionary alloc] initWithDictionary:tempDic];
                node.nodeID = ANY2NSSTRING(tempDic[@"id"]);
                node.parentID = parentNode.nodeID;
                NSNumber *value = tempDic[@"isPerson"];
                node.isPerson = [value intValue]==1 ? YES : NO;
                NSArray *arr = [self getChildrenByNode:node];
                node.isLeaf = arr.count>0 ? NO : YES;
                [parentNode.childArr addObject:node];
            }
        }
        return filteredArr;
    }
    
    /**
     更新数据源
     */
    - (void)updateDataSourceBy:(BIDNode *)node atIndex:(NSUInteger)index
    {
        if(node.isPerson) return;
        NSArray *arr = nil;
        if(node.isExpand)//已展开
        {
            node.isExpand = NO;
            arr = node.childArr;
            if(arr.count>0)
            {
                NSArray *arr = [node getAllRelatedChildNode];
                for(BIDNode *node in arr)
                {
                    node.isExpand = NO;
                }
                [self.dataSourceArr removeObjectsInArray:arr];
                [self.myTableView reloadData];
            }
        }
        else//还未展开
        {
            node.isExpand = YES;
            arr = node.childArr;
            if(arr.count>0)
            {
                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index+1, arr.count)];
                [self.dataSourceArr insertObjects:arr atIndexes:indexSet];
                [self.myTableView reloadData];
            }
        }
    }
    //未使用
    - (void)getRelatedNodesWith:(BIDNode *)selectNode
    {
        NSArray *childArr = selectNode.childArr;
        for(BIDNode *childNode in childArr)
        {
            [self getRelatedNodesWith:childNode];
        }
        [_relatedNodeArr addObjectsFromArray:childArr];
    }

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArr.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSUInteger row = indexPath.row;
    BIDNode *node = self.dataSourceArr[row];
    static NSString *identifier = @"identifier";
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDAddressBookCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDAddressBookCell *addressBookCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    addressBookCell.nameLabel.text = node.data[@"name"];
    if(node.isPerson)
    {
        addressBookCell.imgView.image = nil;
    }
    else
    {
        if(node.isExpand)
        {
            addressBookCell.imgView.image = [UIImage imageNamed:@"expand.png"];
        }
        else
        {
            addressBookCell.imgView.image = [UIImage imageNamed:@"unexpand.png"];
        }
    }
    addressBookCell.stepWidth = 26;
    addressBookCell.stepLevel = node.level;
    addressBookCell.isPerson = node.isPerson;
    addressBookCell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell = addressBookCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    BIDNode *node = self.dataSourceArr[row];
    if(node.isPerson)
    {
        BIDMemberDetailViewController *vc = [[BIDMemberDetailViewController alloc] initWithNibName:@"BIDMemberDetailViewController" bundle:nil];
        vc.memberId = node.nodeID;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        [self updateDataSourceBy:node atIndex:row];
    }
}

@end
